import sys
import os
import datetime

#nodes var vnodes = [{ data: {id:"yo490_cid",label:"Sake",col:"purple",type:"parent",shape:"rectangle",size:"100"}},
#edges var vlinks = [{ data: { id: "e0_cid", source: "yo490_cid", target: "yo512_cid"}},
"""
ACS gra 55902
ACS gra 55902
ac[c] dir ACS
ACS dir accoa[c]
ACSm gra 84532
"""


def is_int(a):
    try:
        int (a)
        return True
    except:
        return False

if (len(sys.argv) < 4):
	print "Usage is python makeNodesEdges.py project pathway sif_file [edge_config_file] rxns_multiple[0,1]"
	sys.exit(-1)

project = sys.argv[1]
pathway = sys.argv[2]
siffile = sys.argv[3]
if (len(sys.argv) == 5):
	edge_configfile = sys.argv[4]
else:
	edge_configfile = "none"

rxns_multiple = 1
if (len(sys.argv) == 6):
	rxns_multiple = int(sys.argv[5])

#print "Processing " + pathway + " " + siffile
nf = open(siffile, "r")
genehash = {}
#will need to read in genehash file first
nodehash = {} 
rxnhash = {}
metahash = {}
linkhash = {}
edgephash = {}
highlight_genes = {}

pathway_longname = siffile.split(".")[0]
nout = "../data/" + project + "_sif_graphs.js"

nfo = open(nout, "a+")
wnodestr = project + 'sifdata["' + project + '_' + pathway + '_nodes"] = ['
wlinkstr = project + 'sifdata["' + project + '_' + pathway + '_links"] = ['
nodestr = "var vnodes = ["
linkstr = "var vlinks = ["

eid = 0
ct = 0
"""
source-arrow-shape : The shape of the edge's arrow on the source side; may be tee, triangle, square, circle, diamond, or none.
source-arrow-color : The colour of the edge's arrow on the source side.
target-arrow-shape : The shape of the edge's arrow on the target side; may be tee, triangle, square, circle, diamond, or none.
target-arrow-color : The colour of the edge's arrow on the target side.
line-color : The colour of the edge's line.
"""
#gene hash 
#100     ADA

if (os.path.isfile("../data/GenesHighlight.txt")):
	hf = open("../data/GenesHighlight.txt", "r")
	for l in hf.readlines():
		htk = l.strip().split(",");
		for hi in htk:
			highlight_genes[hi] = "on"
	hf.close()	

#edge color thickness
if (edge_configfile != "none" and os.path.isfile(edge_configfile) == True):
	edgef = open(edge_configfile, "r")
	for el in edgef.readlines():
		el = el.replace(',','-')
		tk = el.strip().split("\t")
		if (edgephash.get(tk[0]) == None):
			edgephash[tk[0]] = tk[1:]
		else:
			print "edge join ,".join(tk) 
	edgef.close()

gf = open("../data/recon1entrez2symbol.txt", "r")
for line in gf.readlines():
	tk = line.strip().split("\t")
	genehash[tk[0]] = tk[1]
gf.close()

"""
data: {
        nodes: [ { id: "n1", label: "Node 1", score: 1.0 },
                 { id: "n2", label: "Node 2", score: 2.2 },
                 { id: "n3", label: "Node 3", score: 3.5 } ],
        edges: [ { id: "e1", label: "Edge 1", weight: 1.1, source: "n1", target: "n3" },
                 { id: "e2", label: "Edge 2", weight: 3.3, source:"n2", target:"n1"} ]
    }
"""

#keep track of genes in multiple gra reactions
pnf = open(siffile, "r")
grxn = {}
#put third token in hash as key, and add to array
for line in pnf.readlines():
	#line = line.replace("'", "")
	psif = line.strip()
	ptoken = psif.split(" ")
	pgene = ptoken[2]
	rtype = ptoken[1]
	rxn = ptoken[0]
	if (is_int(pgene) and grxn.get(pgene) != None and rtype != "trgt"):
		rarray = grxn.get(pgene)
		rarray.append(rxn)
		grxn[pgene] = rarray
		#print pgene + " size " + str(rarray)
	elif (rtype != "trgt"):
		rarray = []
		rarray.append(rxn)
		grxn[pgene] = rarray
pnf.close()

for rx in grxn:
	parr = grxn.get(rx)
	#print parr # - differentiate adipocte and huvec
	if (len(parr) > 1 and rxns_multiple == 1):
		rxnimage = "images/" + project + "/" + pathway + "/" + rx + "_RXNS.png"
		for pi in parr:
			rxnimage = rxnimage + ",images/" + project + "/" + pathway + "/" + rx + "_" + pi + ".png"
		grxn[rx] = rxnimage
		#print rx + " " + rxnimage
	else:
		grxn[rx] = None 

for line in nf.readlines():
	line = line.replace(',','-')
	line = line.replace("'","")
	sif = line.strip()
	token = sif.split(" ")
	n1 = token[0]
	n2 = token[2]
	dir = token[1]
	add2 = 0
	eid = eid + 1
	image = ''
	if (nodehash.get(n1) == None):
		nodehash[n1] = "1"
		type = "rxn"
		shape = "ellipse"
		height = 40
		width = 40
		col = "green"
		label = n1
		hl = '0'
		if (n1.find("[") != -1):
			type = "metabolite"
			height = 20
			width = 20
			shape = "triangle"
			col = "purple"
		elif (is_int(n1)):
			label = genehash[n1]
			type = "gene"
			width = 80
			height = 50
			col = "blue"
			shape = "rectangle"
			imageUrl = 'images/' + project + "/" + pathway + '/' + n1 + '_' + n2 + '.png'
			if (not os.path.exists("../" + imageUrl)):
                                print " **MISSING** " + imageUrl  
				cmd = "cp ../images/place_holder.png " + "../" + imageUrl
				imageUrl = 'images/place_holder.png' 
				os.system(cmd) 
                        imageUrl = ',image:"' + imageUrl + '"'
			if (grxn.get(n1) != None):
				#print grxn[n1]
				imageUrl = ',image:"' + grxn[n1] + '"'   
				#imageUrl = imageUrl[:-1] + ',' + grxn[n1] + '"'
				#print imageUrl
			if (highlight_genes.get(n1) != None):
				hl = '1'
		elif (n1.find("miR") == 0):
			label = n1
                        type = "mirna"
                        width = 120
                        height = 50
                        col = "blue"
                        shape = "parallelogram" 
		if (type != "gene"):
			imageUrl = ',image:""'
		wnodestr = wnodestr + '{id:"%s_%s",type:"%s",hl:"%s",label:"%s"%s},\n' %(pathway,n1,type,hl,label,imageUrl)
		ct = ct + 1
		add2 = 1 
	if (nodehash.get(n2) == None):
		nodehash[n2] = "1"
                type = "rxn"
                shape = "ellipse"
		label = n2
                col = "green"
		hl = "0"
                if (n2.find("[") != -1):
                        type = "metabolite"
                        shape = "triangle"
                        col = "purple"
                elif (is_int(n2)):
			label = genehash[n2]
			#print n2 + " gene " + label + " " + n1
                        type = "gene"
                        col = "blue"
                        shape = "rectangle"
			imageUrl = 'images/' + project + "/" + pathway + '/' + n2 + '_' + n1 + '.png'
			if (not os.path.exists("../" + imageUrl)):
				print " **MISSING** " + imageUrl
				cmd = "cp ../images/place_holder.png ../" + imageUrl	
				imageUrl = 'images/place_holder.png'
				os.system(cmd)
			imageUrl = ',image:"' + imageUrl + '"' 
			if (grxn.get(n2) != None):
                                imageUrl = ',image:"' + grxn[n2] + '"' 
				#print imageUrl
			if (highlight_genes.get(n2) != None):
                                hl = '1'
		elif (n2.find("miR") == 0):
                        label = n2
                        type = "mirna"
                        width = 120
                        height = 50
                        col = "blue"
                        shape = "parallelogram"
                if (type != "gene"):
                        #imageUrl = ''#',image:""' 
			imageUrl = ',image:""'
		add2 = 1
		ct = ct + 1
		wnodestr = wnodestr + '{id:"%s_%s",type:"%s",hl:"%s",label:"%s"%s},\n' %(pathway,n2,type,hl,label,imageUrl)
	col = "black" 
	thickness = "1"
	if (edgephash != {}):
		col = edgephash[sif][0]		
		thickness = edgephash[sif][1]
	arrow = sif.split(" ")[1]
	dash = "0"
	if (thickness == "-1"):
		dash = "1"
	#linkstr = linkstr + '{ data: { id:"e_%i",source:"%s",target:"%s",col:"%s",thick:"%s",arr:"%s"}},\n' %(eid, "nid_" + n1, "nid_" + n2, col, thickness, arrow)
	wlinkstr = wlinkstr + '{ id:"e%i",dash:"%s",source:"%s",target:"%s",col:"%s",thick:"%s",arr:"%s"},\n' %(eid, dash, pathway+"_" + n1, pathway + "_" + n2, col, thickness, arrow)
        
nfo.write(wnodestr[0:len(wnodestr)-2] + "];\n")
nfo.write(wlinkstr[0:len(wlinkstr)-2] + "];\n")
#<option size='+0' value="AlaAspMet_sif">AlaAspMet (SIF)</option>

print("<option size='+0' value='%s_%s_sif'>%s (SIF)</option>" %(project, pathway, pathway))    
nf.close()
nfo.close()     
